/**
 * time：20024-4-15
 * name：meidusa
 * role：图片压缩
 */

import { Options } from "./type";

/**
 * 读取图片信息
 * @param e 参数
 */
const GetImgInfo = (e: any) => {
  const target = e.target as HTMLInputElement;
  const fileObj = target.files?.[0];
  if (fileObj) {
    new CompressImage({
      file: fileObj,
      quality: 1,
      succress: (base64) => {
        document.body.innerHTML = `<img src="${base64}">`;
      },
    });
  }
};

/**
 * 压缩图片
 */
class CompressImage {
  options: Options;
  fileReader = new FileReader(); // 创建读取器
  constructor(options: Options) {
    this.options = options;
    this.CreateBase64();
  }

  // 创建base64
  CreateBase64() {
    this.fileReader.onload = (e) => {
      this.Compress(e.target?.result as string);
    };
    this.fileReader.readAsDataURL(this.options.file); // 将file传进去就会返回base64
  }

  // 压缩
  Compress(url: string) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();
    img.src = url;
    img.onload = () => {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx?.drawImage(img, 0, 0, img.width, img.height);
      const base64 = canvas.toDataURL("image/jpeg", this.options.quality);
      this.options.succress?.(base64);
    };
  }
}

export { GetImgInfo };
